<?php


namespace app\user\controller;

use think\Db;
use think\facade\Request;

/**
 * Class Contract 合同
 * @package app\user\controller
 */
class Contract extends LoggingBase
{
    #region 文件列表
    /**
     * 界面：文件列表
     */
    public function FileListing()
    {
        $Css = array(
            '<link href="/layui/css/layui.css" rel="stylesheet"/>'
        );
        return $this->mb_Display('文件列表', 'ContracFiletList', 'file_list', $Css);
    }

    /**
     * 界面：分组列表
     */
    public function GroupListing()
    {
        return $this->fetch('group_list');
    }
    /**
     * 接口：新增文件分組
     */
    public function mb_AddGroup()
    {
        $Name = Request::has('Name') ? Request::param('Name') : '';
        if (!$Name) mb_OutMessage(ErrCode_Toast, '请填写分组名称');

        $CompanyID = $this->m_User->CompanyID;

        $Count = Db::table('company_group_file')->where("IsDeleted='0' AND CompanyID='$CompanyID' AND Name='$Name'")->count('ID');
        if($Count>0)mb_OutMessage(ErrCode_Toast,'该分组已添加');

        Db::startTrans();
        try {
            Db::table('company_group_file')->insert(array(
                'CompanyID' => $CompanyID,
                'Name' => $Name
            ));
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
        mb_OutMessage(ErrCode_Normal, '添加成功');
    }

    /**
     * 文件分组列表
     */
    public function mb_GroupListing()
    {
        $CompanyID = $this->m_User->CompanyID;
        $Page = Request::has('page') ? Request::param('page') : 1;
        $Limit = Request::has('limit') ? Request::param('limit') : 10;
        $Count = Db::table('company_group_file')->where("IsDeleted='0' AND CompanyID='$CompanyID'")->count();
        $Data = Db::table('company_group_file')->where("IsDeleted='0' AND CompanyID='$CompanyID'")->page($Page)->limit($Limit)->select();
        mb_OutMessage(ErrCode_Normal, '', $Data, $Count);
    }

    /**
     * 刪除文件分組
     */
    public function mb_DeleteGroup()
    {
        $GroupID = Request::has('GroupID') ? Request::param('GroupID') : '';
        $DeleteFiles = Request::has('DeleteFiles') ? Request::param('DeleteFiles') : 0; //是否删除该分组下的文件 0:否，1：是
        if(!$GroupID)mb_OutMessage(ErrCode_Toast,'参数有误!');

        Db::startTrans();
        try {
            Db::table('company_group_file')->update(['ID' => $GroupID, 'IsDeleted' => '0']);
            if($DeleteFiles){
                //删除分组下的文件
                Db::table('company_file')->where("GroupID='$GroupID'")->update(['IsDeleted' => 1]);
            } else {
                //不删除分组下的文件
                Db::table('company_file')->where("GroupID='$GroupID'")->update(['GroupID' => 0]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
    }

    /**
     * 新增文件
     */
    public function mb_AddFile()
    {
        $CompanyID = $this->m_User->CompanyID;
        $GroupID = Request::has('GroupID') ? Request::param('GroupID') : 0;
        $Name = Request::has('Name') ? Request::param('Name') : '';
        $Remark = Request::has('Remark') ? Request::param('Remark') : '';
        $FileUrl = Request::has('FileUrl') ? Request::param('FileUrl') : '';

        if($Name == '' || $FileUrl == '')mb_OutMessage(ErrCode_Toast,'参数有误!');

        Db::startTrans();
        try {
            $Data = array(
                'CompanyID'=>$CompanyID,
                'GroupID'=>$GroupID,
                'Name'=>$Name,
                'Remark'=>$Remark,
                'FileUrl'=>$FileUrl
            );
            Db::table('company_file')->insert($Data);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
        mb_OutMessage(ErrCode_Normal,'保存成功');
    }

    /**
     * 文件列表
     */
    public function mb_FileListing()
    {
        $Page = Request::has('page') ? Request::param('page') : 1;
        $Limit = Request::has('limit') ? Request::param('limit') : 10;
        $Keyword = Request::has('Keyword') ? Request::param('Keyword') : '';

        $OrderField = Request::has('OrderField') ? Request::param('OrderField') : '';
        $OrderType = Request::has('OrderType') ? Request::param('OrderType') : '';

        $Where = '';
        if ($Keyword != '') {
            $Where .= " AND cf.Name LIKE '%$Keyword%' ";
        }

        if($OrderType == '' || $OrderField == ''){
            $OrderField = 'cf.ID';
            $OrderType = 'DESC';
        } else {
            $OrderField = 'cf.'+$OrderField;
        }

        $CompanyID = $this->m_User->CompanyID;
        $Count = Db::table('company_file')->where("IsDeleted='0' AND CompanyID='$CompanyID' $Where ")->count();
        $Data = Db::table('company_file')->field('cf.ID,cf.Name,cf.FileUrl,cf.TimeCreated,cf.Remark,cgf.Name as GroupName')->alias('cf')->leftJoin('company_group_file cgf','cgf.ID=cf.GroupID')->where("cf.IsDeleted='0' AND cf.CompanyID='$CompanyID' $Where ")->page($Page, $Limit)->order($OrderField, $OrderType)->select();
        mb_OutMessage(ErrCode_Normal, '', $Data, $Count);
    }

    #endregion

    #region 合同列表

    /**
     * 界面：合同列表
     */
    public function Listing()
    {
        $UserID = $this->m_User->ID;
        $CompanyID = $this->m_User->CompanyID;
        //搜索我的客戶
        $Data = Db::table('client')->field('ID,Name,Contacts,Phone')->where("IsDeleted='0' AND OwnerType='1' AND OwnerID='$UserID'")->select();
        $this->assign('Clients', $Data);
        //公司員工
        $Data = Db::table('user')->field('u.ID,u.Name,u.Nick,u.Phone,cd.Name AS DepartmentName')->alias('u')->leftJoin('company_department cd', 'cd.ID=u.DepartmentID')->where("u.IsDeleted='0' AND u.CompanyID='$CompanyID'")->select();
        $this->assign('Users', $Data);

        $this->assign('Today', date('Y-m-d'));

        $this->assign('UserID', $UserID);
        $Css = array(
            '<link href="/layui/css/layui.css" rel="stylesheet"/>'
        );
        return $this->mb_Display('合同列表', 'ContractList', 'contract_list', $Css);
    }

    /**
     * 接口：合同列表
     */
    public function mb_Listing()
    {
        $Page = Request::has('page') ? Request::param('page') : 1;
        $Limit = Request::has('limit') ? Request::param('limit') : 9999999;
        $Type = Request::has('Type') ? Request::param('Type') : 0;  //0：全部，1：我提交的，2：我签订的，3：我审核的
        $Keyword = Request::has('Keyword') ? Request::param('Keyword') : '';

        $OrderField = Request::has('OrderField') ? Request::param('OrderField') : '';
        $OrderType = Request::has('OrderType') ? Request::param('OrderType') : 'null';

        $ClientID = Request::has('ClientID') ? Request::param('ClientID') : 0;

        if ($OrderType == 'null') {
            $OrderField = 'ID';
            $OrderType = 'desc';
        }

        $UserID = $this->m_User->ID;
        $Where = '';
        if ($Keyword != '') {
            $Where .= " AND (c.Name LIKE '%$Keyword%' OR cr.Number LIKE '%$Keyword%' OR cr.Name LIKE '%$Keyword%') ";
        }
        if ($Type == 0) {
            $Where .= " AND (cr.UserID='$UserID' OR cr.AuditorID='$UserID' OR cr.SignerID='$UserID') ";
        } else if ($Type == 1) {
            $Where .= " AND cr.UserID='$UserID' ";
        } else if ($Type == 2) {
            $Where .= " AND cr.SignerID='$UserID' ";
        } else if ($Type == 3) {
            $Where .= " AND cr.AuditorID='$UserID' ";
        }

        if($ClientID != 0){
            $Where .= " AND cr.ClientID='$ClientID' ";
        }

        $Count = Db::table('contract')->field('cr.ID')->alias('cr')->leftJoin('client c', 'c.ID=cr.ClientID')->where("cr.IsDeleted='0' $Where")->count();
        $Data = Db::table('contract')->field('cr.ID,cr.Number,cr.Name,c.Name AS ClientName,cr.Money,cr.Begin,cr.End,us.Nick AS SignerName,ua.ID AS AuditorID, ua.Nick AS AuditorName,cr.Status,cr.FileUrls')->alias('cr')
            ->leftJoin('client c', 'c.ID=cr.ClientID')
            ->leftJoin('user us', 'us.ID=cr.SignerID')
            ->leftJoin('user ua', 'ua.ID=cr.AuditorID')
            ->where("cr.IsDeleted='0' $Where")->order($OrderField, $OrderType)->page($Page)->limit($Limit)->select();

        foreach ($Data as $Key => $Val) {
            $Data[$Key]['Begin'] = date('Y-m-d', strtotime($Val['Begin']));
            $Data[$Key]['End'] = date('Y-m-d', strtotime($Val['End']));
            switch ($Val['Status']) {
                case 1:
                    $Data[$Key]['StatusName'] = '草稿';
                    break;
                case 2:
                    $Data[$Key]['StatusName'] = '待審核';
                    break;
                case 3:
                    $Data[$Key]['StatusName'] = '審核通過';
                    break;
                case 4:
                    $Data[$Key]['StatusName'] = '審核不通過';
                    break;
                default:
                    $Data[$Key]['StatusName'] = '草稿';
                    break;
            }
        }
        mb_OutMessage(ErrCode_Normal, '', $Data, $Count);
    }

    /**
     * 接口：新增或编辑合同
     */
    public function mb_Submit()
    {
        $UserID = $this->m_User->ID;
        $CompanyID = $this->m_User->CompanyID;
        $ContractID = Request::has('ContractID') ? Request::param('ContractID') : 0;    //0：新增，Other:编辑
        $Number = Request::has('Number') ? Request::param('Number') : '';
        $Name = Request::has('Name') ? Request::param('Name') : '';
        $ClientID = Request::has('ClientID') ? Request::param('ClientID') : 0;
        $Money = Request::has('Money') ? Request::param('Money') : 0;
        $SignerID = Request::has('SignerID') ? Request::param('SignerID') : 0;
        $AuditorID = Request::has('AuditorID') ? Request::param('AuditorID') : 0;
        $Status = Request::has('Status') ? Request::param('Status') : 0;    //（1：草稿，2：待審核，3：審核通過，4：審核不通過）
        $FileUrls = Request::has('FileUrls') ? Request::param('FileUrls') : '';
        $Begin = Request::has('Begin') ? Request::param('Begin') : '';
        $End = Request::has('End') ? Request::param('End') : '';

        if ($Name == '') mb_OutMessage(ErrCode_Toast, '请输入合同名称');
        if ($ClientID == 0) mb_OutMessage(ErrCode_Toast, '请选择客户');

        $Data = array(
            'UserID' => $UserID,
            'Number' => $Number,
            'Name' => $Name,
            'ClientID' => $ClientID,
            'Money' => $Money,
            'SignerID' => $SignerID,
            'AuditorID' => $AuditorID,
            'Status' => $Status,
            'FileUrls' => $FileUrls,
            'Begin' => $Begin,
            'End' => $End
        );

        Db::startTrans();
        try {
            if ($ContractID == 0) {
                //新增
                $Client = Db::table('client')->field('ID,Name')->where("IsDeleted='0' AND OwnerType='1' AND OwnerID='$UserID' AND ID='$ClientID'")->find();
                if ($Client == null) mb_OutMessage(ErrCode_Toast, '该客户不存在，请选择正确客户');

                $Signer = Db::table('user')->field('ID,Name')->where("IsDeleted='0' AND ID='$SignerID' AND CompanyID='$CompanyID'")->find();
                if ($Signer == null) mb_OutMessage(ErrCode_Toast, '该公司签约人不存在，请选择正确签约人');

                $Auditor = Db::table('user')->field('ID,Name')->where("IsDeleted='0' AND ID='$AuditorID' AND CompanyID='$CompanyID'")->find();
                if ($Auditor == null) mb_OutMessage(ErrCode_Toast, '该审核人不存在，请选择正确审核人');

                $ID = Db::table('contract')->insertGetId($Data);
                if ($Number == '') {
                    Db::table('contract')->update(array(
                        'ID' => $ID,
                        'Number' => 'CONTRACT-' . $ID
                    ));
                }
            } else {
                //編輯
                $Data['ID'] = $ContractID;
                if ($Number == '') {
                    $Data['Number'] = 'CONTRACT-' . $ContractID;
                }
                Db::table('contract')->update($Data);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
        mb_OutMessage(ErrCode_Normal, '保存成功');
    }
    #endregion
}